﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace HobSoft.SoccerBet2014.Common.Collection
{
    using Errors;
    public static class EnumerableExtensions
    {
        public static bool IsEmpty<T>(this IEnumerable<T> source)
        {
            source.IsNull().ThrowNull("source");
            return !source.Any();
        }

        public static bool IsEmpty<T>(this IEnumerable<T> source, Func<T, bool> predicate)
        {
            source.IsNull().ThrowNull("source");
            return !source.Any(predicate);
        }

        public static T Max<T>(this IEnumerable<T> source, IComparer<T> comparer)
        {
            source.IsNull().ThrowNull("source");
            source.IsEmpty().IsTrue().ThrowInvalidOperation("source must has elements.");

            T maxItem = default(T);
            if (maxItem == null)
            {
                foreach (T item in source)
                {
                    if (item != null && (maxItem == null || comparer.Compare(item, maxItem) > 0))
                        maxItem = item;
                }
                return maxItem;
            }
            var first = true;
            foreach (var item in source)
            {
                if (first)
                {
                    maxItem = item;
                    first = false;
                }
                else
                {
                    if (comparer.Compare(item, maxItem) > 0)
                        maxItem = item;
                }
            }
            return maxItem;
        }

        public static T Min<T>(this IEnumerable<T> source, IComparer<T> comparer)
        {
            source.IsNull().ThrowNull("source");
            source.IsEmpty().IsTrue().ThrowInvalidOperation("source must has elements.");

            T minItem = default(T);
            if (minItem == null)
            {
                foreach (T item in source)
                {
                    if (item != null && (minItem == null || comparer.Compare(item, minItem) < 0))
                        minItem = item;
                }
                return minItem;
            }
            var first = true;
            foreach (var item in source)
            {
                if (first)
                {
                    minItem = item;
                    first = false;
                }
                else
                {
                    if (comparer.Compare(item, minItem) < 0)
                        minItem = item;
                }
            }
            return minItem;
        }
    }
}
